package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private ServerSocket serverSocket;

    private Map<String,PrintWriter> allOut = Collections.synchronizedMap(new HashMap<>());

    public Server(){
        try {
            System.out.println("正在启动服务器...");
            ServerSocket serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void Start(){
        try {
            while(true){
                System.out.println("等待客户连接...");
                Socket socket = serverSocket.accept();
                System.out.println(socket.getInetAddress().getHostAddress()+"用户已连接");
                ClientHanderler clientHanderler = new ClientHanderler(socket);
                Thread thread = new Thread(clientHanderler);
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class ClientHanderler implements Runnable{
        private Socket socket;
        private String host;
        private String nickName;

        public ClientHanderler(){
        }

        public ClientHanderler(Socket socket){
            this.socket = socket;
            this.host = socket.getInetAddress().getHostAddress();
        }

        public void run(){
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                nickName = br.readLine();

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);

                allOut.put(nickName, pw);

                String line;
                while((line = br.readLine()) != null){

                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                allOut.remove(nickName);
                sendMessage(nickName+"("+host+")下线了!");
            }
        }

        public void sendMessage(String message){
            System.out.println(message);
            allOut.values().forEach(o->o.println(message));
        }
    }
}
